import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "qrc:/qml/styles" as Styles
import "qrc:/qml/components" as Components

Rectangle {
    id: kpiPanel

    // 自定义属性
    property var dashboardViewModel: null
    property bool autoRefresh: true
    property int refreshInterval: 5000  // 5秒刷新一次

    // 默认样式
    color: "transparent"

    // KPI数据
    property var kpiData: [
        {
            key: "agvOnline",
            title: qsTr("在线AGV"),
            value: dashboardViewModel && dashboardViewModel.activeAgvCount !== undefined ? dashboardViewModel.activeAgvCount.toString() : "0",
            unit: qsTr("台"),
            subtitle: qsTr("总计 %1 台").arg(dashboardViewModel ? dashboardViewModel.totalAgvCount || dashboardViewModel.activeAgvCount : "0"),
            color: Styles.Theme.success,
            icon: "🚛",
            trend: "none",
            trendValue: 0
        },
        {
            key: "tasksExecuting",
            title: qsTr("执行中任务"),
            value: dashboardViewModel && dashboardViewModel.executingTaskCount !== undefined ? dashboardViewModel.executingTaskCount.toString() : "0",
            unit: qsTr("个"),
            subtitle: qsTr("今日完成 %1 个").arg(dashboardViewModel ? dashboardViewModel.completedTasksToday || 0 : "0"),
            color: Styles.Theme.info,
            icon: "⚙️",
            trend: "up",
            trendValue: 2.3
        },
        {
            key: "tasksPending",
            title: qsTr("待处理任务"),
            value: dashboardViewModel && dashboardViewModel.pendingTaskCount !== undefined ? dashboardViewModel.pendingTaskCount.toString() : "0",
            unit: qsTr("个"),
            subtitle: qsTr("最高优先级 %1").arg(dashboardViewModel ? dashboardViewModel.highestPriority || "低" : "低"),
            color: Styles.Theme.warning,
            icon: "📋",
            trend: "down",
            trendValue: 1.2
        },
        {
            key: "systemThroughput",
            title: qsTr("系统吞吐量"),
            value: dashboardViewModel && dashboardViewModel.throughputPerHour !== undefined ? dashboardViewModel.throughputPerHour.toFixed(1) : "0.0",
            unit: qsTr("任务/小时"),
            subtitle: qsTr("过去1小时平均"),
            color: Styles.Theme.primary,
            icon: "📊",
            trend: "up",
            trendValue: 5.8
        },
        {
            key: "errorRate",
            title: qsTr("错误率"),
            value: dashboardViewModel && dashboardViewModel.errorRate !== undefined ? (dashboardViewModel.errorRate * 100).toFixed(1) : "0.0",
            unit: "%",
            subtitle: qsTr("过去24小时"),
            color: dashboardViewModel && dashboardViewModel.errorRate > 0.05 ? Styles.Theme.danger : Styles.Theme.success,
            icon: "⚠️",
            trend: dashboardViewModel && dashboardViewModel.errorRate > 0.05 ? "up" : "down",
            trendValue: 0.3
        },
        {
            key: "avgBattery",
            title: qsTr("平均电量"),
            value: dashboardViewModel && dashboardViewModel.averageBatteryLevel !== undefined ? Math.round(dashboardViewModel.averageBatteryLevel).toString() : "100",
            unit: "%",
            subtitle: qsTr("最低电量 %1%").arg(dashboardViewModel ? Math.round(dashboardViewModel.lowestBatteryLevel) : "100"),
            color: (function() {
                var level = dashboardViewModel ? dashboardViewModel.averageBatteryLevel : 100;
                if (level > 50) return Styles.Theme.success;
                if (level > 20) return Styles.Theme.warning;
                return Styles.Theme.danger;
            })(),
            icon: "🔋",
            trend: "none",
            trendValue: 0
        }
    ]

    // 布局
    Flow {
        anchors.fill: parent
        spacing: Styles.Theme.spacingNormal

        Repeater {
            model: kpiData

            Components.KpiCard {
                title: modelData.title
                value: modelData.value
                unit: modelData.unit
                subtitle: modelData.subtitle
                valueColor: modelData.color
                iconSource: modelData.icon
                trend: modelData.trend
                trendValue: modelData.trendValue
                loading: dashboardViewModel ? dashboardViewModel.isLoading : false

                onClicked: {
                    console.log("KPI card clicked:", modelData.key)
                    handleKpiClick(modelData.key)
                }
            }
        }
    }

    // 自动刷新定时器
    Timer {
        interval: refreshInterval
        running: autoRefresh && dashboardViewModel && dashboardViewModel.isInitialized
        repeat: true
        onTriggered: {
            if (dashboardViewModel) {
                dashboardViewModel.refreshDashboard()
            }
        }
    }

    // 处理KPI卡片点击
    function handleKpiClick(key) {
        switch(key) {
            case "agvOnline":
                // 导航到车辆管理页面
                console.log("Navigate to vehicle management")
                break;
            case "tasksExecuting":
            case "tasksPending":
                // 导航到任务管理页面
                console.log("Navigate to task management")
                break;
            case "systemThroughput":
                // 显示详细的吞吐量统计
                console.log("Show throughput details")
                break;
            case "errorRate":
                // 导航到日志中心显示错误
                console.log("Navigate to log center")
                break;
            case "avgBattery":
                // 显示AGV电量详情
                console.log("Show battery details")
                break;
            default:
                break;
        }
    }

    // 手动刷新方法
    function refresh() {
        if (dashboardViewModel) {
            dashboardViewModel.refreshDashboard()
        }
    }

    // 暂停/恢复自动刷新
    function setAutoRefresh(enabled) {
        autoRefresh = enabled
    }

    // 设置刷新间隔
    function setRefreshInterval(milliseconds) {
        refreshInterval = milliseconds
    }
}